package com.ziytek.web.citizen.util;

import org.yaml.snakeyaml.Yaml;

import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Map;

public class YamlUtils {
    // 配置文件路径
    private final Path yamlPath = Paths.get("src/main/resources/application-dev.yml");

    // 读取 YAML 文件内容为 Map
    public static Map<String, Object> readYaml(Path yamlPath) throws Exception {

        if (null == yamlPath) {
            yamlPath = Paths.get("config/application-dev.yml");
        }
        try (InputStream inputStream = Files.newInputStream(yamlPath)) {
            Yaml yaml = new Yaml();
            return yaml.load(inputStream);
        }
    }

    // 遍历 Map 结构
    public static void traverseYaml(Map<String, Object> yamlMap) {
        yamlMap.forEach((key, value) -> {
            System.out.println("Key: " + key);
            if (value instanceof Map) {
                // 递归遍历嵌套结构
                traverseYaml((Map<String, Object>) value);
            } else {
                System.out.println("Value: " + value);
            }
        });
    }

    // 修改 Map 中的配置值
    public static void modifyYaml(Map<String, Object> yamlMap, String keyPath, Object newValue) {
        String[] keys = keyPath.split("\\.");
        Map<String, Object> current = yamlMap;
        for (int i = 0; i < keys.length - 1; i++) {
            current = (Map<String, Object>) current.get(keys[i]);
        }
        current.put(keys[keys.length - 1], newValue);
    }

    // 保存修改后的 Map 到文件
    public static void saveYaml(Path yamlPath, Map<String, Object> yamlMap) throws Exception {

        if (null == yamlPath) {
            yamlPath = Paths.get("config/application-dev.yml");
        }
        Yaml yaml = new Yaml();
        String updatedYaml = yaml.dumpAsMap(yamlMap);
        Files.write(yamlPath, updatedYaml.getBytes(), StandardOpenOption.TRUNCATE_EXISTING);
    }

}
